package com.yifi.common;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Hashtable;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class ZxingUtils {
	/**
	 * 条形码编码
	 * 
	 * @param contents
	 * @param width
	 * @param height
	 * @param imgPath
	 */
	public static void enBarcode(String content, int width, int height, String imgPath) {
		int codeWidth = 3 + // start guard
				(7 * 6) + // left bars
				5 + // middle guard
				(7 * 6) + // right bars
				3; // end guard
		codeWidth = Math.max(codeWidth, width);
		try {
			BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
					BarcodeFormat.CODE_39, codeWidth, height, null);

			MatrixToImageWriter.writeToStream(bitMatrix, "png",
					new FileOutputStream(imgPath));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 解析条形码
	 * 
	 * @param imgPath
	 * @return
	 */
	public static String deBarcode(String imgPath) {
		BufferedImage image = null;
		Result result = null;
		try {
			image = ImageIO.read(new File(imgPath));
			if (image == null) {
				System.out.println("the decode image may be not exit.");
			}
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

			result = new MultiFormatReader().decode(bitmap, null);
			return result.getText();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	/**
	 * 生成二维码
	 * 
	 * @param contents
	 * @param width
	 * @param height
	 * @param imgPath
	 */
	public static void enQRcode(String content, int width, int height, String imgPath) {
		Map<EncodeHintType, Object> hints = new Hashtable<>();
		// 指定纠错等级
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
		// 指定编码格式
		hints.put(EncodeHintType.CHARACTER_SET, "GBK");
		try {
			BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
					BarcodeFormat.QR_CODE, width, height, hints);

			MatrixToImageWriter.writeToStream(bitMatrix, "png",
					new FileOutputStream(imgPath));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void enQRcode1(String content, int width, int height, String imgPath) {
		Map<EncodeHintType, Object> hints = new Hashtable<>();
		// 指定纠错等级
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		// 指定编码格式
		hints.put(EncodeHintType.CHARACTER_SET, "GBK");
		hints.put(EncodeHintType.MARGIN, 0);
		try {
			BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
					BarcodeFormat.QR_CODE, width, height, hints);
			
			int[] rec = bitMatrix.getEnclosingRectangle();  

			int resWidth = rec[2] + 1;  

			int resHeight = rec[3] + 1;  

			BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);  

			resMatrix.clear();  

			for (int i = 0; i < resWidth; i++) {  

			    for (int j = 0; j < resHeight; j++) {  

			        if (bitMatrix.get(i + rec[0], j + rec[1])) { 

			             resMatrix.set(i, j); 

			        } 

			    }  

			}  

			//2

			 width = resMatrix.getWidth();

			 height = resMatrix.getHeight();

			BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB);

			for (int x = 0; x < width; x++) {

			    for (int y = 0; y < height; y++) {

			        image.setRGB(x, y, resMatrix.get(x, y) == true ? 

			        Color.BLACK.getRGB():Color.WHITE.getRGB());

			    }

			}
			
			
			ImageIO.write(image,"png", new File(imgPath));
			
		//	MatrixToImageWriter.writeToStream(bitMatrix, "png",
				//	new FileOutputStream(imgPath));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 解析二维码
	 * 
	 * @param imgPath
	 * @return
	 */
	public static String deQRcode(String imgPath) {
		BufferedImage image = null;
		Result result = null;
		try {
			image = ImageIO.read(new File(imgPath));
			if (image == null) {
				System.out.println("the decode image may be not exit.");
			}
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

			Map<DecodeHintType, Object> hints = new Hashtable<>();
			hints.put(DecodeHintType.CHARACTER_SET, "GBK");

			result = new MultiFormatReader().decode(bitmap, hints);
			return result.getText();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 根据传的内容生成 Qrcode  返回 二维码
	 * @param cname
	 * @param content
	 * @return
	 */
	public static String getQrcode(String cname,String content,int width) {
		String QRcodePath = IOHelper.getWebUploadPath() + "\\codeImg\\";
		File dataFile = new File(QRcodePath);
		// 判断文件夹是否存在,如果不存在则创建文件夹
		if (!dataFile.exists()) {
			dataFile.mkdir();
		}
		//生成二维码
		//QRCodeUtils.encoderQRCode(content, QRcodePath+content + ".png");
		ZxingUtils.enQRcode(content, width, width, QRcodePath+cname + ".png");
		QRcodePath="codeImg/";
		
		//照片访问路径为 WEB-INF里的图片不能使用路径访问
		return  QRcodePath+ cname + ".png";
		
		//return "/QRcode/00040200021.png";
	}
}
